<template>
  <view id="box" class="flex-col">
    <Item 
		:list="typeList"
		v-model="selectedObjs"
		:valueKey="valueKey"
		@itemClick="itemClick"
	></Item>
    <!-- <view class="dl select flex-row justify-start align-center"
		style="border-bottom-width: 0px;margin-top: 5px;">
      <view class="dt">已选条件：</view>
      <view class="dd" v-for="(item,index) in selectedObjs" :key="index">
        {{ item[textKey] }}
      </view>
    </view> -->
  </view>
</template>

<script>
import { defineAsyncComponent } from 'vue'
import { traverseTree } from "@/framework/utils"
import Item from './item'
export default {
  name: 'typeItem',
  components: {
	Item
  },
  props: {
	isLevelTitle: {
		type: Boolean,
		default: () => false
	},
    typeList: {},
    returnObj: {
      type: Boolean,
      default: () => false
    },
    textKey: {
      type: String,
      default: () => 'name'
    },
    valueKey: {
      type: String,
      default: () => 'id'
    },
    modelValue: {
		type: String,
		default: () => ''
	}
  },
  data(){
    return {
      selectedObjs: [],
      selectedIds: ''
    }
  },
  watch: {
    selectedObjs: {
      handler(val){
		if(this.returnObj){
			this.$emit('update:modelValue', val)
		} else {
			const values = val?.map(item => item[this.valueKey]).join(',')
			this.selectedIds = values
			this.$emit('update:modelValue', values)
		}
      },
      deep: true,
      immediate: true
    },
	modelValue: {
      handler(val){
		if(val?.length > 0){
			this.selectedObjs = [...this.setSelect(val)]
		}
	  },
	  deep: true,
	  immediate: true
	},
  },
  methods: {
    itemClick(item, list){
      this.$emit('itemClick',item, list)
    },
	setSelect(val){
		if(typeof val === "string"){
		  const idSet = new Set(val?.split(',') ||[])
		  return this.setSelectList(idSet)
		} else {
		  const ids = val?.map(item => item[this.valueKey]).join(',')
		  const idSet = new Set(ids?.split(',') ||[])
		  return this.setSelectList(idSet)
		}
	},
	setSelectList(idSet){
		const tList = []
		traverseTree(this.typeList,(item) => {
		  const idval = item[this.valueKey]
		  if( idSet?.has(item[this.valueKey]) ){
			  tList.push(item)
		  }
		})
		return tList
	}
  }
}
</script>

<style scoped lang="scss">
.dl.select {
  // background: #efefef;
  margin: 0;
  padding: 0px 20px 8px;
}

.dl.select .dd {
  border: 1px solid #409eff;
  border-radius: 3px;
  // background-color: #fff;
  padding: 2px 12px;
  margin-left: 12px;
  font-size: 0.9rem;
  cursor: pointer;
}

.dl.select .dd span {
  width: 20px;
  height: 20px;
  display: inline-block;
  text-align: center;
  line-height: 20px;
  background: #c4284d;
  color: #fff;
  margin-left: 10px;
  cursor: pointer;
  border-radius: 5px;
}
</style>



